from backend.api import (
    get_account,
    get_account_info,
    get_exchange,
    get_orders,
    get_positions,
    get_trade_histories,
    operate_order,
    operate_position,
)
import pandas as pd
import streamlit as st


if __name__ == "__main__":
    with st.sidebar:
        exchange = st.selectbox("选择交易所", get_exchange())
        if exchange:
            account = st.selectbox("选择账户", get_account(exchange))

    st.title("账户信息")

    st.subheader("基础信息")
    info = get_account_info(exchange, account)
    if st.button("刷新基础信息"):
        get_account_info.clear()
    info_df = pd.DataFrame(
        data=list(info.items()),
        columns=["键", "值"],
    )
    st.dataframe(info_df, selection_mode="multi-row", hide_index=True)

    st.subheader("仓位信息")
    position_df = pd.DataFrame(get_positions())
    if st.button("刷新仓位"):
        get_positions.clear()
    choose_positions = st.dataframe(
        position_df, on_select="rerun", selection_mode="multi-row"
    )
    choose_pos_df = position_df.iloc[choose_positions.selection.rows]
    if st.button("平仓"):
        operate_position(choose_pos_df.to_dict())
        st.success("平仓成功")
        get_positions.clear()

    st.subheader("订单信息")
    order_df = pd.DataFrame(get_orders())
    if st.button("刷新订单"):
        get_orders.clear()
    choose_orders = st.dataframe(
        order_df, on_select="rerun", selection_mode="multi-row"
    )
    choose_order_df = order_df.iloc[choose_orders.selection.rows]
    if st.button("取消订单"):
        operate_order(choose_order_df.to_dict())
        st.success("取消成功")
        get_orders.clear()

    st.subheader("交易记录")
    trade_df = pd.DataFrame(get_trade_histories())
    st.dataframe(trade_df)
